package com.cyzy.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ElasticsearchException;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.TotalHits;
import com.cyzy.dto.ResponseDto;
import com.cyzy.esbean.ContentsIndex;
import com.cyzy.service.ContentsIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author LIGHT
 */
@RestController
@RequestMapping("/es")
public class EsController {

    private static final Logger logger = Logger.getLogger(EsController.class.getName());
    private static final String INDEX_NAME = "contents_index";

    @Autowired
    private ElasticsearchClient client;
    @Autowired
    private ContentsIndexService contentsIndexService;

    @RequestMapping("/search")
    public ResponseDto search(@RequestParam("keyword") String keyword) {
        contentsIndexService.initIndex();

        List<Object> resList = new ArrayList<>();

        try {
            SearchResponse<ContentsIndex> response = client.search(searchReq ->
                            searchReq.index(INDEX_NAME)
                                    .query(query -> query.match(
                                            field -> field.field("content").query(keyword))),
                    ContentsIndex.class);

            TotalHits total = response.hits().total();
            logger.info("找到 " + total.value() + " 条匹配记录");
            System.out.println("64------------"+total.value());

            List<Hit<ContentsIndex>> hits = response.hits().hits();
            for (Hit<ContentsIndex> hit : hits) {
                ContentsIndex contentsIndex = hit.source();
                if (contentsIndex != null) {
                    resList.add(contentsIndex);
                }
            }

        } catch (ElasticsearchException e) {
            if (e.response().error().type().equals("index_not_found_exception")) {
                logger.warning("索引不存在: " + INDEX_NAME);
                return ResponseDto.fail("索引不存在，请稍后再试");
            }
            logger.severe("Elasticsearch 搜索错误: " + e.getMessage());
            return ResponseDto.fail("搜索服务暂时不可用");
        } catch (IOException e) {
            logger.severe("IO 错误: " + e.getMessage());
            return ResponseDto.fail("搜索请求处理失败");
        }

        return ResponseDto.ok(resList);
    }
}